package com.kly.smartbi.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

@Component
@Slf4j
public class SendEmailUtil {

    // 发件人邮箱地址和密码
    @Value("${email.fromEmail}")
    private String fromEmail;

    @Value("${email.password}")// Sender's email
    private String password;

    /**
     * 发送邮件
     * @param toEmail
     * @param subject
     * @param content
     */
    private void sendEmail(String toEmail, String subject, String content) {
        // 1. 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true"); // 使用TLS
        properties.put("mail.smtp.host", "smtp.qq.com"); // SMTP服务器地址
        properties.put("mail.smtp.port", "587"); // SMTP端口


        // 2. 创建会话
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        });

        try {

            // 3. 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject(subject);

            // 4. 创建邮件正文
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(content, "text/html;charset=utf-8"); // 可以使用HTML格式
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);
            message.setContent(multipart);
            // 5. 发送邮件
            Transport.send(message);
            log.info("邮件发送成功");
        } catch (MessagingException e) {
            log.error("邮件发送失败");
            e.printStackTrace();
        }
    }
    /**
     * 发送邮件
     * @param toEmail
     * @param verificationCode
     */
    public void sendCodeEmail(String toEmail, String verificationCode) {
        // 2. 动态替换占位符
        String companyName = "鹿七科技";
        String contactEmail = "2693176405@qq.com";
        String contactPhone = "400-123-4567";
        // 读取文件
        String code_info = ResourceUtil.readUtf8Str("email_code_info.txt");
        code_info = code_info
                .replace("【VERIFICATION_CODE】", verificationCode)
                .replace("【COMPANY_NAME】", companyName)
                .replace("【CONTACT_EMAIL】", contactEmail)
                .replace("【CONTACT_PHONE】", contactPhone);
        // 复用发送邮件的方法
        sendEmail(toEmail, "【鹿七科技】验证码", code_info);
    }

}
